package cn.gson.crm.service.impl;

import cn.gson.crm.bo.MiniChatLoginBo;
import cn.gson.crm.exception.MiniApiException;
import cn.gson.crm.model.dao.UserDao;
import cn.gson.crm.model.domain.UserEntity;
import cn.gson.crm.service.IUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by wangxiangyun on 2020/4/26.
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Value("${wechat.openid.url}")
    private String openIdUrl;
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.secret}")
    private String secret;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserDao userDao;

    @Override
    public UserEntity findUserByOpenId(String openId) {
        UserEntity userEntity = userDao.findByOpenIdAndDeleted(openId, 0);
        return userEntity;
    }

    @Override
    public void save(UserEntity userEntity) {
        userEntity.setDeleted( 0);
        userEntity.setCreateTime(new Timestamp(new Date().getTime()));
        userDao.save(userEntity);
    }

    @Override
    public String miniChatLogin(MiniChatLoginBo miniChatLoginBo) {
        String openIdUrl = String.format(this.openIdUrl, appId, secret, miniChatLoginBo.getCode());
        String resultStr = restTemplate.getForObject(openIdUrl, String.class);
        log.info("小程序用户详情：{}",resultStr);
        JSONObject resultJson = JSON.parseObject(resultStr);
        String openId=resultJson.getString("openid");
        String sessionKey=resultJson.getString("session_key");
        if(StringUtils.isEmpty(openId)){
            throw  new MiniApiException("微信获取openId异常");
        }
        UserEntity user=  this.findUserByOpenId(openId);
        if(user==null){
            UserEntity userEntity=new UserEntity();
            userEntity.setOpenId(openId);
            userEntity.setAvatarUrl(miniChatLoginBo.getAvatarUrl());
            userEntity.setGender(miniChatLoginBo.getGender());
            userEntity.setNickName(miniChatLoginBo.getNickName());
            this.save(userEntity);
        }
        //生成token 存入redis
        String token = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(token, JSONObject.toJSONString(user),30, TimeUnit.MINUTES);
        return token;
    }
}
